package cn.tedu.csmall.passport.exception.handler;

import cn.tedu.csmall.commons.exception.ServiceException;
import cn.tedu.csmall.commons.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import static cn.tedu.csmall.commons.web.ServiceCode.*;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult ServiceException(ServiceException e){
        log.warn("程序运行过程中出现了ServiceException，将统一处理！");
        log.warn("异常信息为：{}",e.getMessage());
        return JsonResult.fail(e.getServiceCode(),e.getMessage());
    }

    @ExceptionHandler
    public JsonResult ConstraintViolationException(ConstraintViolationException e){
        log.warn("程序运行过程中出现了ConstraintViolationException，将统一处理！");
        log.warn("异常信息为：{}",e.getMessage());
        String message=null;
        for (ConstraintViolation<?> constraintViolation : e.getConstraintViolations()) {
            message=constraintViolation.getMessage();
        }
        return JsonResult.fail(ERR_BAD_REQUEST,message);
    }

    @ExceptionHandler
    public JsonResult BindException(BindException e){
        log.warn("程序运行过程中出现了BindException，将统一处理！");
        log.warn("异常信息为：{}",e.getMessage());
        String message=e.getFieldError().getDefaultMessage();
        return JsonResult.fail(ERR_BAD_REQUEST,message);

        // StringJoiner stringJoiner = new StringJoiner("，", "请求参数错误，", "！");
        // List<FieldError> fieldErrors = e.getFieldErrors();
        // for (FieldError fieldError : fieldErrors) {
        //    String defaultMessage = fieldError.getDefaultMessage();
        //    stringJoiner.add(defaultMessage);
        // }
        // return stringJoiner.toString();

//        List<String> messageList = new ArrayList<>();
//        List<FieldError> fieldErrors = e.getFieldErrors();
//        for (FieldError fieldError : fieldErrors) {
//            String defaultMessage = fieldError.getDefaultMessage();
//            messageList.add(defaultMessage);
//        }
//        return messageList;
    }

    @ExceptionHandler
    public JsonResult MissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.warn("程序运行过程中出现了MissingServletRequestParameterException，将统一处理！");
        log.warn("异常信息为：{}", e.getMessage());
        String message = "参数不能为空";
        return JsonResult.fail(ERR_BAD_REQUEST, message);
    }
    @ExceptionHandler
    public JsonResult handleThrowable(Throwable e){
        log.warn("程序运行过程中出现了Throwable，将统一处理！");
        log.warn("异常信息为：{}",e.getMessage());
        log.warn("异常:",e);
        String message="服务器忙，请稍后再试！【在开发过程中，如果看到此提示，应该检查服务器端的控制台，分析异常，并在全局异常处理器中补充处理对应异常的方法】";

        return JsonResult.fail(ERR_UNKNOWN,message);
    }

    @ExceptionHandler({
            InternalAuthenticationServiceException.class,
            BadCredentialsException.class
    })
    public JsonResult AuthenticationException(AuthenticationException e) {
        log.warn("程序运行过程中出现了AuthenticationException，将统一处理！");
        log.warn("异常信息为：{}", e.getMessage());
        String message="登录失败，用户名或密码错误!";
        return JsonResult.fail(ERR_UNAUTHORIZED,message);
    }
    @ExceptionHandler
    public JsonResult DisabledException(DisabledException e) {
        log.warn("程序运行过程中出现了DisabledException，将统一处理！");
        log.warn("异常信息为：{}", e.getMessage());
        String message="登录失败，用户名已被禁用!";
        return JsonResult.fail(ERR_UNAUTHORIZED_DISABLED, message);
    }
    @ExceptionHandler
    public JsonResult AccessDeniedException(AccessDeniedException e) {
        log.warn("程序运行过程中出现了AccessDeniedException，将统一处理！");
        log.warn("异常信息为：{}", e.getMessage());
        String message="该管理员无此权限，禁止访问!";
        return JsonResult.fail(ERR_FORBIDDEN, message);
    }
}
